package com.hopes.bizz.hazard.job;

import com.hopes.bizz.hazard.enterprises.service.HazEnterprisesMsgService;
import com.hopes.bizz.hazard.enterprises.service.HazEnterprisesRtService;
import com.hopes.bizz.hazard.support.HazEnterprisesMsgGenerateSupport;
import com.hopes.boss.admin.api.entity.SysCompanyEntity;
import com.hopes.boss.admin.api.feign.RemoteCompanyService;
import com.hopes.boss.common.core.constant.SecurityConstants;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author daijie
 * @version 1.0
 * @date 2024/2/1 16:28
 * @Description: 企业风险预警消息生成任务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class HazEnterprisesMsgGenerateService {

    @Autowired
    private RemoteCompanyService remoteCompanyService;
    private final HazEnterprisesMsgGenerateSupport generateSupport;
    private final HazEnterprisesMsgService hazEnterprisesMsgService;
    private final HazEnterprisesRtService hazEnterprisesRtService;

    @Transactional(rollbackFor = Exception.class)
    @XxlJob("hazEnterprisesMsgGenerateJobHandler")
    public void hazEnterprisesMsgGenerateJobHandler() {
        long start = System.currentTimeMillis();

        List<SysCompanyEntity> orgList = remoteCompanyService.list(SecurityConstants.FROM_IN).getData();
        for (SysCompanyEntity sysCompanyEntity : orgList) {
            Long orgId = sysCompanyEntity.getId();
            // 1. 平均扰动率(20分)
            Integer disturbanceRateAvg = generateSupport.calDisturbanceRateAvg(orgId);
            // 2. 重复报警点位数(20分)
            Integer repeatedAlarmPoints = generateSupport.calRepeatedAlarmPoints(orgId);
            // 3. 点位平均报警次数(20分)
            Integer alarmPointAvg = generateSupport.calAlarmPointAvg(orgId);
            // 4. 平均消警时长(20分)
            Integer alarmDurationAvg = generateSupport.calAlarmDurationAvg(orgId);
            // 5. 消警处置及时率(20分)
            Integer alarmHandlingRate = generateSupport.calAlarmHandlingRate(orgId);

            Integer score = disturbanceRateAvg + repeatedAlarmPoints + alarmPointAvg + alarmDurationAvg + alarmHandlingRate;
            // 6. 根据总分更新企业实时风险并判断是否需要生成预警消息
            generateSupport.updateEnterprisesRt(orgId, score, disturbanceRateAvg,
                    repeatedAlarmPoints, alarmPointAvg, alarmDurationAvg, alarmHandlingRate);
        }

        log.info("----------------企业风险预警消息生成结束,耗时(毫秒)={}----------------`",  System.currentTimeMillis() - start);
        // 设置任务结果
        XxlJobHelper.handleSuccess();
    }
}
